var alarmFlag, portFlag;//0为添加1为更新
//设备类型 0:标杆; 1:标杆; 2:信号灯; 3:信号机; 4:太阳能产品; 5:限高杆; 6:标线; 7:护栏; 8:监控箱; 9:井盖;
var gDeviceType = ["标杆", "标杆", "信号灯", "信号机", "太阳能", "限高杆", "标线", "护栏", "监控箱", "井盖"]
var localOrgId = 0;
var dtDeviceType = -2;
var firstOrgId;
var currentActorId = 3;
if (gUserLoginResult.userActors.indexOf("7") >= 0) currentActorId = 7;
if (gUserLoginResult.userActors.indexOf("1") >= 0) currentActorId = 1;

var gActorId = gUserLoginResult.userActors.includes("1") ? 1 : 2;
var gBindDeviceId = null;

function _debounce(fn, delay) {
    var timer
    return function () {
        var context = this
        var args = arguments
        clearTimeout(timer)
        timer = setTimeout(function () {
            fn.apply(context, args)
        }, delay)
    }
}

$(function () {
    $.getOrgList = function (tag) {
        var html = "", result = "";
        $.ajax({
            url: "../rds_fault/getOrg4Select",
            type: "post",
            async: false,
            data: {
                actorId: gActorId,
                orgId: gUserLoginResult.orgId
            },
            success: function (msg) {
                if (msg) {
                    if (msg.isSuccess) {
                        var jsonData = msg.jsonData;
                        var orglist = "";
                        if (jsonData.length == 0) {
                            firstOrgId = gUserLoginResult.orgId;
                            result = "<option value='" + gUserLoginResult.orgId + "'>" + gUserLoginResult.orgName + "</option>"
                        }
                        else {

                            for (var i in jsonData) {
                                orglist += "," + jsonData[i].orgId;
                                html += "<option value='" + jsonData[i].orgId + "'>" + jsonData[i].orgName + "</option>"
                            }
                            orglist = orglist.substr(1);
                            if (gActorId == 1) {
                                if (!tag) {
                                    result += "<option value='-2'>全部</option>";
                                }
                                result += "<option value='-1'>未设置</option>";
                                firstOrgId = -2;
                            }
                            else {
                                firstOrgId = orglist
                                result += "<option value='" + orglist + "'>全部</option>"
                            }
                            result += html;
                        }

                    }

                }
            }
        })
        return result;
    }

    var html = $.getOrgList();
    gMainDT = $("#mainDataTable").DataTable({
        ajax: {
            url: "../rds_alarmManage/getAlarm4DT",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.orgId = firstOrgId;
                d.actorId = gActorId;
                d.deviceType = dtDeviceType;

            }
        },
        columns: [{
            data: "alarmId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: null,
            targets: 0
        }, {
            data: "deviceId"

        }, {
            data: "deviceState",
            render: function (data, type, row) {
                if (data == 0) return "离线";
                else return "在线";
            }
        }, {
            data: "ruleGroupName",
            render: function (data, type, row) {
                if (data)
                    return "<button class='btn btn-default btn-xs btn-flat' onclick='$.showRule(" + row.deviceModel + ")'>" + data + "</button>"
                else
                    return "暂无"
            }
        }, {
            data: "deviceManufacturer"
        }, {
            data: "deviceAddress"
        }, {
            data: "orgName",
            render: function (data) {
                if (data)
                    return data;
                else
                    return "未设置"
            }
        }, {
            data: "createTime"
        }, {
            data: "updateTime"
        }, {
            data: "deviceType",
            render: function (data, type, row) {
                var result = "";
                if (data == -1 || data == null)
                    return "未绑定设备";
                else {
                    result += gDeviceType[data] + ":" + row.devicePathId
                    var html1 = "<button class='btn btn-default btn-xs btn-flat' onclick='$.showDeviceInfo(" + data + "," + row.devicePathId + ")' " +
                        "title=''>" + result + "</button>";
                    return html1;
                }
            }
        }, {
            data: "alarmId",
            render: function (data, type, row) {
                var updateButton = "<button class='btn btn-primary btn-xs btn-flat'" +
                    "onclick='$.updateAlarm(" + JSON.stringify(row) + ")' title='编辑'>" +
                    "<i class='fa fa-edit'></i></button>";
                var cmdButton = "<button class='btn btn-primary btn-xs btn-flat'" +
                    "onclick='$.sendCmd(" + row.deviceId + ")' title='指令控制'>" +
                    "<i class='fa fa-code'></i></button>";
                var deleteButton = "<button class='btn btn-primary btn-xs Fbtn-flat'" +
                    "onclick='$.deleteAlarm(" + data + ")' title='删除'>" +
                    "<i class='fa fa-minus-square'></i></button>";
                var recordButton = "<button class='btn btn-primary btn-xs btn-flat'" +
                    "onclick='$.showRecord(" + row.deviceId + ")' title='查看日志'>" +
                    "<i class='glyphicon glyphicon-list-alt'></i></button>";
                var ruleButton = "<button class='btn btn-primary btn-xs btn-flat'" +
                    "onclick='$.boundingDevice(" + JSON.stringify(row) + ")' title='设备绑定'>" +
                    "<i class='glyphicon glyphicon-th-list'></i></button>";
                return updateButton + "&nbsp" + cmdButton + "&nbsp" + recordButton + "&nbsp" + ruleButton + "&nbsp" + deleteButton;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' " +
                "data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
                "<span class='caret'></span><span class='sr-only'>切换下拉</span></button>" +
                "<ul class='dropdown-menu'>" +
                "<li>" +
                "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>" +
                "</li>";

            var buttonAdd = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.addAlarm()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonAdd;
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.deleteAlarm(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            /* 2:信号灯; 3:信号机; 4:太阳能产品; 5:限高杆;; 8:监控箱*/
            strToolBar += "</ul></div> " +
                "<div class='input-group-sm' style='display:inline-block'>" +
                "<select class='form-control ' style='width: 160px' id='org4Select'></select>&nbsp;" +
                "<select class='form-control ' style='width: 80px' id='typeSelect'>" +
                "<option value='-2'>全部</option>" +
                "<option value='-1'>未设定</option>" +
                "<option value='2'>信号灯</option>" +
                "<option value='3'>信号机</option>" +
                "<option value='4'>太阳能</option>" +
                "<option value='5'>限高杆</option>" +
                "<option value='8'>监控箱</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 150px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$.searchDT()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            $("#mainToolbar").append(strToolBar);

            $("#deviceOrgId").append($.getOrgList(1));
            $("#org4Select").append(html);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(1).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });
    var oTable = $('#mainDataTable').dataTable();
    if (gActorId == 1) {
        oTable.fnSetColumnVis(9, false);
    } else {
        oTable.fnSetColumnVis(7, false);
    }


    $("#calculate").click(function () {
        var shortTime=$("#ShortTimePeriod").val();
        var longTime=$("#LongTimePeriod").val();
        var result=shortTime*0.02*longTime;
        $("#my_sum").html("周期=("+shortTime+" * 0.02 ) * "+longTime+" = "+result+" s ");
    })

});

$.showDeviceInfo = function (deviceType, deviceId) {
    $.ajax({
        url: "../rds_alarmManage/getDeviceInfo",
        type: "post",
        data: {
            deviceType: deviceType,
            deviceId: deviceId
        },
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess) {
                    var jsonData = msg.jsonData;
                    if (deviceType == 2)
                        $.showSignalLampInfo(jsonData[0]);
                    else if (deviceType == 3)
                        $.showSignalMachineInfo(jsonData[0]);
                    else if (deviceType == 4)
                        $.showSolarEnergyInfo(jsonData[0]);
                    else if (deviceType == 5)
                        $.showHighLeverInfo(jsonData[0]);
                    else
                        $.showMonitorInfo(jsonData[0]);
                } else {
                    $.alert("获取信息失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    })
}

$.checkChange = function () {
    var isChecked = $("#batchCheck").prop('checked');
    $("input:checkbox[id^='checkbox']").prop("checked", isChecked);
};

$.searchDT = function () {
    firstOrgId = $("#org4Select").val();
    dtDeviceType = $("#typeSelect").val();
    gMainDT.search(null).draw();
}


var ruleModelDt, rule_content = "", rule_time = ""
$("#deviceModelBtn").click(function () {
    ruleModelDt = $("#rule_model_table").DataTable({
        ajax: {
            url: "../rds_ruleGroup/getRuleGroup4DT",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.content = rule_content;
                d.time = rule_time;
            }
        },
        columns: [{
            data: "ruleGroupId",
        }, {
            data: "ruleGroupType",
            render: function (data) {
                if (data == -1)
                    return "通用";
                else
                    return gDeviceType[data];
            }
        }, {
            data: "ruleGroupName"
        }, {
            data: "ruleGroupRemarks"
        }, {
            data: "ruleCreateTime",
            render: function (data) {
                return data.substr(0, 10)
            }
        }, {
            data: "ruleGroupId",
            render: function (data, type, row) {
                return "<button onclick='$.selectRuleModel(" + data + ",\"" + row.ruleGroupName + "\")' class='btn btn-primary btn-xs btn-flat' title='选中'><i class='glyphicon glyphicon-ok'></i></button>";
            }
        }],
        dom: "<'row'<'col-md-4'l><'#ruleToolBar.col-md-8'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        }
    });
    $("#rule-modal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
})

$.selectRuleModel = function (data, detail) {
    $("#deviceModel").val(data);
    $("#deviceModelDetail").val(detail);
    $("#rule-modal").modal("hide");

}


$("#redRuleTable").on('click', '#rebRuleCheckBox', function () {
    var isChecked = $(this).prop('checked');
    $("input:checkbox[id^='redCheckbox']").prop("checked", isChecked);
})
$("#blueRuleTable").on('click', '#blueRuleCheckBox', function () {
    var isChecked = $(this).prop('checked');
    $("input:checkbox[id^='blueCheckbox']").prop("checked", isChecked);
})


$.sendCmd = function (deviceId) {
    $("#cmd_deviceId").val(deviceId);
    $("#cmd").hide();
    $("#setParaBtn").hide();
    $("#modal-cmd").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};


$("#cmdSelect").change(function () {
    if ($(this).val() == 3) {
        $("#cmd").show();
        $("#setParaBtn").show();

    }
    else {
        $("#cmd").hide();
        $("#setParaBtn").hide();
    }
})

$.addAlarm = function () {
    alarmFlag = 0;
    $("#createUser").val(gUserLoginResult.userId);
    if (gUserLoginResult.userActors != 1)
        $("#deviceOrgId").val(gUserLoginResult.orgId);

    $("#deviceState").val(0);
    $("#modal-alarm").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

$("#setParaBtn").click(function () {
    $("#inputTypeId").val(1);
    $(".setpara").show();
    $(".setkey").hide();
    $("#modal-para").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
});

$('#form-para').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    }, fields: {
        Min_Transient: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '请输入数字'
                }
            }
        },
        Min_Mediacy: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '请输入数字'
                }
            }
        },
        Min_Final: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '请输入数字'
                }
            }
        },
        ShortTimePeriod: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '请输入数字'
                }
            }
        },
        LongTimePeriod: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '请输入数字'
                }
            }
        },
        key: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '请输入数字'
                }
            }
        },
    }
}).on('success.form.bv', function (e) {

    if ($("#inputTypeId").val() == "1") {
        var cmd = "NBsvr setpara ";
        cmd += $("#Min_Transient").val() + "," + $("#Min_Mediacy").val() + "," + $("#Min_Final").val() + "," + $("#ShortTimePeriod").val() + "," + $("#LongTimePeriod").val();
        gCycleTime = $("#LongTimePeriod").val();
    } else {
        var cmd = "NBsvr setkey ";
        cmd += $("#key").val()
        gCycleTime = null;
    }

    $("#cmd").val(cmd);
    $.clearModal($('#form-para'), $('#modal-para'));


});
var gCycleTime = 0;


$.boundingDevice = function (jsonData) {
    $("#deviceType").val(-1);
    $("#showNone").show()
    $("#bounding-body1").html("");
    if (jsonData.deviceType >= 0) {
        $("#boundingDevice").html("绑定设备:" + gDeviceType[jsonData.deviceType] + "." + jsonData.devicePathId);
        gBindDeviceId = jsonData.devicePathId;
    }
    else {
        $("#boundingDevice").html("未绑定设备");
        gBindDeviceId = null;
    }
    $("#boundingAlarmId").val(jsonData.deviceId)
    $("#modal-bounding").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}

/**
 * @Description:
 * @Author: WYX.
 * @Date: 2018/5/19 15:45.
 */
var deviceListDT, toolBarRoadName = "", startRoad4Select = "", endRoad4Select = "", alarmBinding, localActorId
$.loadDeviceId = function (deviceType) {
    $.getOrgList = function () {
        var html = "", result = "";
        $.ajax({
            url: "../rds_fault/getOrg4Select",
            type: "post",
            async: false,
            data: {
                actorId: gActorId,
                orgId: gUserLoginResult.orgId
            },
            success: function (msg) {
                if (msg) {
                    if (msg.isSuccess) {
                        var jsonData = msg.jsonData;
                        var orglist = "";
                        if (jsonData.length == 0) {
                            firstOrgId = gUserLoginResult.orgId;
                            result = "<option value='" + gUserLoginResult.orgId + "'>" + gUserLoginResult.orgName + "</option>"
                        }
                        else {

                            for (var i in jsonData) {
                                orglist += "," + jsonData[i].orgId;
                                html += "<option value='" + jsonData[i].orgId + "'>" + jsonData[i].orgName + "</option>"
                            }
                            orglist = orglist.substr(1);
                            if (gActorId == 1) {
                                result += "<option value='-2'>全部</option>" +
                                    "<option value='-1'>未设置</option>"
                                firstOrgId = -2;
                            }
                            else {
                                firstOrgId = orglist
                                result += "<option value='" + orglist + "'>全部</option>"
                            }
                            result += html;
                        }

                    }

                }
            }
        })
        return result;
    }
    var html2 = $.getOrgList();
    var bound_deviceId;
    if ($("#boundingAlarmId").val())
        bound_deviceId = $("#boundingAlarmId").val();
    else
        bound_deviceId = null
    var html1 = "<table id='deviceListDataTable' class='table table-striped table-bordered'cellspacing='0' width='100%'>" +
        "<thead><tr><th>序号</th><th>图片</th><th>设备号</th><th>地址</th><th>状态</th><th>操作</th></tr></thead>";
    $("#bounding-body1").html(html1);
    var device_Id = "", device_Photo = "";
    var device_Info = "";
    if (deviceType == 2) {
        device_Id = "signalLampId";
        device_Photo = "signalLampPhoto";
    } else if (deviceType == 3) {
        device_Id = "signalMachineId";
        device_Photo = "signalMachinePhoto";
    } else if (deviceType == 4) {
        device_Id = "solarEnergyId";
        device_Photo = "solarEnergyPhoto";
    } else if (deviceType == 5) {
        device_Id = "highLeverId";
        device_Photo = "highLeverPhoto";
    } else if (deviceType == 8) {
        device_Id = "monitorId";
        device_Photo = "monitorPhoto";
    }
    localOrgId = gUserLoginResult.orgId;
    localActorId = currentActorId;
    deviceListDT = $("#deviceListDataTable").DataTable({
        ajax: {
            url: "../rds_alarmManage/getDeviceIdList",
            type: 'post',
            data: function (d) {
                d.search = "";
                d.roadName = toolBarRoadName;
                d.startRoad = startRoad4Select;
                d.endRoad = endRoad4Select;
                d.actorId = localActorId;
                d.orgId = localOrgId;
                d.deviceType = deviceType;
                d.audit = false;
                d.alarmBinding = alarmBinding;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: device_Photo,
            render: function (data, type, row) {
                return "<img src='" + data + "' style='width: 50px; height: 40px; cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + data + "\")'>";
            }
        }, {
            data: device_Id
        }, {
            data: null,
            render: function (data, type, row) {
                switch (deviceType) {
                    case "2":
                        return row.signalLampProvince + " " + row.signalLampCity + " " + row.signalLampArea + " " + row.signalLampStartRoad + "--" + row.signalLampEndRoad;
                        break;
                    case "3":
                        return row.signalMachineProvince + " " + row.signalMachineCity + " " + row.signalMachineArea + " " + row.signalMachineStartRoad + "--" + row.signalMachineEndRoad;
                        break;
                    case "4":
                        return row.solarEnergyProvince + " " + row.solarEnergyCity + " " + row.solarEnergyArea + " " + row.solarEnergyRoadName + " " + row.solarEnergyStartRoad + "--" + row.solarEnergyEndRoad;
                        break;
                    case "5":
                        return row.highLeverProvince + " " + row.highLeverCity + " " + row.highLeverArea + " " + row.highLeverRoadName + " " + row.highLeverStartRoad + "--" + row.highLeverEndRoad;
                        break;
                    case "8":
                        return row.monitorProvince + " " + row.monitorCity + " " + row.monitorArea + " " + row.monitorRoadName + " " + row.monitorStartRoad + "--" + row.monitorEndRoad;
                        break;
                }
            }
        }, {
            data: null,
            render: function (data, type, row) {
                if (row.alarmDeviceId) {
                    return "已绑定" + row.alarmDeviceId;
                } else {
                    return "未绑定报警器";
                }
            }
        }, {
            data: device_Id,
            render: function (data, type, row) {
                var disable1 = "", disable2 = "";
                if (row.alarmDeviceId != null)
                    disable1 = "disabled";
                else
                    disable2 = "disabled";
                if (deviceType == 2) {
                    device_Info = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showSignalLampInfo(" + JSON.stringify(row) + ")' title='信息查看'>" +
                        "<i class='glyphicon glyphicon-eye-open'></i></button> ";
                } else if (deviceType == 3) {
                    device_Info = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showSignalMachineInfo(" + JSON.stringify(row) + ")' title='信息查看'>" +
                        "<i class='glyphicon glyphicon-eye-open'></i></button> ";
                } else if (deviceType == 4) {
                    device_Info = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showSolarEnergyInfo(" + JSON.stringify(row) + ")' title='信息查看'>" +
                        "<i class='glyphicon glyphicon-eye-open'></i></button> ";
                } else if (deviceType == 5) {
                    device_Info = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showHighLeverInfo(" + JSON.stringify(row) + ")' title='信息查看'>" +
                        "<i class='glyphicon glyphicon-eye-open'></i></button> ";
                } else if (deviceType == 8) {
                    device_Info = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showMonitorInfo(" + JSON.stringify(row) + ")' title='信息查看'>" +
                        "<i class='glyphicon glyphicon-eye-open'></i></button> ";
                }
                return device_Info +
                    "<button class='btn btn-primary btn-xs btn-flat' title='绑定' onclick='$.bindDevice(" + data + "," + bound_deviceId + "," + deviceType + ")' " + disable1 + "><i class='fa fa-link'></i></button>&nbsp;" +
                    "<button class='btn btn-primary btn-xs btn-flat' title='解绑' onclick='$.unbindDevice(" + data + "," + bound_deviceId + "," + deviceType + ")' " + disable2 + "><i class='fa fa-unlink'></i></button>";
            }
        }
        ],
        dom: "<'row'<'col-md-2'l><'#deviceToolbar.col-md-10'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            $("#deviceToolbar").empty();
            $("#deviceToolbar").append(gStrTool);
            $("#org4SearchDevice").append(html2);
            switch (deviceType) {
                case "2":
                    $.getSLRoad(1);
                    break;
                case "3":
                    $.getSMRoad(1);
                    break;
                /*  case "4":
                      $.getSERoad(1);
                      break;
                  case "5":
                      $.getHighLeverStartRoad();
                      break;
                  case "8":
                      $.getMonitorStartRoad();
                      break;*/
            }
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 5,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    })
}

$.Trim = function (str, is_global) {
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g, "");
    if (is_global.toLowerCase() == "g") {
        result = result.replace(/\s/g, "");
    }
    return result;
};

var gStrTool;
$("#deviceType").change(function () {
    var deviceType = $(this).val();
    switch (deviceType) {
        case "2":
            gStrTool = "<div class='input-group-sm' style='float:right'>" +
                "<button href='#' class='btn btn-default btn-flat btn-sm'" +
                "onclick='deviceListDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>&nbsp;" +
                "<select class='form-control ' style='width: 130px' id='org4SearchDevice' onchange='$.getSLRoad(1,this.value);'></select>&nbsp;" +
                "<select onchange='$.getSLRoad(2);'  style='width: 80px' class='form-control mysize' id='startRoad4Select'>" +
                "<option value=''>起/止</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='endRoad4Select'>" +
                "<option value=''>止/起</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='alarm4Select'>" +
                "<option value='0'>报警器</option>" +
                "<option value='1'>已绑定</option>" +
                "<option value='2'>未绑定</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDeviceDTa()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            break
        case "3":
            gStrTool = "<div class='input-group-sm' style='float:right'>" +
                "<button href='#' class='btn btn-default btn-flat btn-sm'" +
                "onclick='deviceListDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>&nbsp;" +
                "<select class='form-control ' style='width: 130px' id='org4SearchDevice' onchange='$.getSMRoad(1,this.value);'></select>&nbsp;" +
                "<select onchange='$.getSMRoad(2);'  style='width: 80px' class='form-control mysize' id='startRoad4Select'>" +
                "<option value=''>起/止</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='endRoad4Select'>" +
                "<option value=''>止/起</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='alarm4Select'>" +
                "<option value='0'>报警器</option>" +
                "<option value='1'>已绑定</option>" +
                "<option value='2'>未绑定</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDeviceDTa()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            break
        case "4":
            gStrTool = "<div class='input-group-sm' style='float:right'>" +
                "<button href='#' class='btn btn-default btn-flat btn-sm'" +
                "onclick='deviceListDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>&nbsp;" +
                "<select class='form-control ' style='width: 130px' id='org4SearchDevice' onchange='$.getSERoad(1)'></select>&nbsp;" +
                "<input id='toolBarRoadName' onkeyup='$getSERoad(1);' type='text' class='form-control mysize' placeholder='路名'>" +
                "&nbsp;<select onchange='$.getSERoad(2);'  style='width: 80px' class='form-control mysize' id='startRoad4Select'>" +
                "<option value=''>起/止</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='endRoad4Select'>" +
                "<option value=''>止/起</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='alarm4Select'>" +
                "<option value='0'>报警器</option>" +
                "<option value='1'>已绑定</option>" +
                "<option value='2'>未绑定</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDeviceDT()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            break
        case "5":
            gStrTool = "<div class='input-group-sm' style='float:right'>" +
                "<button href='#' class='btn btn-default btn-flat btn-sm'" +
                "onclick='deviceListDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>&nbsp;" +
                "<select class='form-control ' style='width: 130px' id='org4SearchDevice' onchange='$.getHighLeverStartRoad()'></select>&nbsp;" +
                "<input id='toolBarRoadName' onkeyup='$getHighLeverStartRoad()'  type='text' class='form-control mysize' placeholder='路名'>" +
                "&nbsp;<select   style='width: 80px' onchange='$.getHighLeverEndRoad()' class='form-control mysize' id='startRoad4Select'>" +
                "<option value=''>起/止</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='endRoad4Select'>" +
                "<option value=''>止/起</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='alarm4Select'>" +
                "<option value='0'>报警器</option>" +
                "<option value='1'>已绑定</option>" +
                "<option value='2'>未绑定</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDeviceDT()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            break
        case "8":
            gStrTool = "<div class='input-group-sm' style='float:right'>" +
                "<button href='#' class='btn btn-default btn-flat btn-sm'" +
                "onclick='deviceListDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>&nbsp;" +
                "<select class='form-control ' style='width: 130px' id='org4SearchDevice' onchange='$.getMonitorStartRoad()'></select>&nbsp;" +
                "<input id='toolBarRoadName' onkeyup='$getMonitorStartRoad()'  type='text' class='form-control mysize' placeholder='路名'>" +
                "&nbsp;<select   style='width: 80px' onchange='$.getMonitorEndRoad()' class='form-control mysize' id='startRoad4Select'>" +
                "<option value=''>起/止</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='endRoad4Select'>" +
                "<option value=''>止/起</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='alarm4Select'>" +
                "<option value='0'>报警器</option>" +
                "<option value='1'>已绑定</option>" +
                "<option value='2'>未绑定</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDeviceDT()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            break
    }
    if (deviceType > 0) {
        $("#showNone").hide()
        $.loadDeviceId(deviceType)
    }
    else {
        $("#showNone").show()
        $("#bounding-body1").html("")
    }
})

$.fn.searchDeviceDT = function () {
    toolBarRoadName = $.Trim($("#toolBarRoadName").val(), "g");
    startRoad4Select = $("#startRoad4Select").val();
    endRoad4Select = $("#endRoad4Select").val();
    alarmBinding = $("#alarm4Select").val();
    localOrgId = $("#org4SearchDevice").val();
    if (localActorId != 7) {
        if (localOrgId == -2) {
            localActorId = 1;
        } else {
            localActorId = 3;
        }
    }
    deviceListDT.search($("#searchText").val()).draw();
};

$.fn.searchDeviceDTa = function () {
    startRoad4Select = $("#startRoad4Select").val();
    endRoad4Select = $("#endRoad4Select").val();
    alarmBinding = $("#alarm4Select").val();
    localOrgId = $("#org4SearchDevice").val();
    if (localActorId != 7) {
        if (localOrgId == -2) {
            localActorId = 1;
        } else {
            localActorId = 3;
        }
    }
    deviceListDT.search($("#searchText").val()).draw();
};

$.getSLRoad = function (type, orgId) {
    if (!orgId)
        orgId = $("#org4SearchDevice").val()
    var id = "endRoad4Select";
    var url = "../rds_signalLampManage/getSectionByStartRoad";
    var roadName = $("#startRoad4Select").find("option:selected").val();
    if (type == 1) {
        url = "../rds_signalLampManage/getStartRoad";
        id = "startRoad4Select";
    }
    var mActorId = currentActorId;
    if (orgId != -2)
        mActorId = 3;
    $.ajax({
        url: url,
        type: "POST",
        data: {
            "roadName": roadName,
            "actorId": mActorId,
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#" + id).empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#" + id).append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#" + id).append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    } else
                        $("#" + id).append("<option>无</option>");
                    if (type == 1) {
                        $.getSLRoad(2);
                    }
                } else {
                    $.alert("获取监管单位数据失败", 2);
                }
            }
        }
    })
};

$.getSMRoad = function (type, orgId) {
    if (!orgId)
        orgId = $("#org4SearchDevice").val()
    var id = "endRoad4Select";
    var url = "../rds_signalMachineManage/getSectionByStartRoad";
    var roadName = $("#startRoad4Select").find("option:selected").val();
    if (type == 1) {
        url = "../rds_signalMachineManage/getStartRoad";
        id = "startRoad4Select";
    }
    var mActorId = currentActorId;
    if (orgId != -2)
        mActorId = 3;
    $.ajax({
        url: url,
        type: "POST",
        data: {
            "roadName": roadName,
            "actorId": mActorId,
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#" + id).empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#" + id).append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#" + id).append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    } else
                        $("#" + id).append("<option>无</option>");
                    if (type == 1) {
                        $.getSMRoad(2);
                    }
                } else {
                    $.alert("获取监管单位数据失败", 2);
                }
            }
        }
    })
};

$.getSERoad = function (type, orgId) {//TODO 太阳能没弄好
    if (!orgId)
        orgId = $("#org4SearchDevice").val()
    var id = "endRoad4Select";
    var url = "../rds_solarEnergyManageController/getSectionByRoadName";
    var roadName = $("#startRoad4Select").find("option:selected").val();
    if (type == 1) {
        url = "../rds_solarEnergyManageController/getRoadByRoadName";
        roadName = $.Trim($("#toolBarRoadName").val(), "g");
        id = "startRoad4Select";
    }
    var mActorId = currentActorId;
    if (orgId != -2)
        mActorId = 3;
    $.ajax({
        url: url,
        type: "POST",
        data: {
            "roadName": roadName,
            "actorId": mActorId,
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#" + id).empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#" + id).append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#" + id).append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    } else
                        $("#" + id).append("<option>无</option>");
                    if (type == 1) {
                        $.getSERoad(2);
                    }
                } else {
                    $.alert("获取监管单位数据失败", 2);
                }
            }
        }
    })
};

$.getHighLeverStartRoad = function (orgId) {
    if (!orgId)
        orgId = $("#org4SearchDevice").val()
    var mActorId = currentActorId;
    if (orgId != -2)
        mActorId = 3;
    $.ajax({
        url: "../rds_HighLeverManage/getStartRoadByRoadName",
        type: "POST",
        data: {
            "roadName": $("#toolBarRoadName").val(),
            "actorIds": mActorId,
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#startRoad4Select").empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#startRoad4Select").append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#startRoad4Select").append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    }
                    else
                        $("#startRoad4Select").append("<option>无</option>");
                } else {
                    $.alert("获取起始道路数据失败", 2);
                }
            }
        }
    })
};

$.getHighLeverEndRoad = function (orgId) {
    if (!orgId)
        orgId = $("#org4SearchDevice").val()
    var mActorId = currentActorId;
    if (orgId != -2)
        mActorId = 3;
    $.ajax({
        url: "../rds_HighLeverManage/getEndRoadByStartRoad",
        type: "POST",
        data: {
            "city": "",
            "highLeverRoadName": $("#toolBarRoadName").val(),
            "startRoad": $("#startRoad4Select").val(),
            "actorIds": mActorId,
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#endRoad4Select").empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#endRoad4Select").append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#endRoad4Select").append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    }
                    else
                        $("#endRoad4Select").append("<option>无</option>");
                } else {
                    $.alert("获取起始道路数据失败", 2);
                }
            }
        }
    })
}

$.getMonitorStartRoad = function (orgId) {
    if (!orgId)
        orgId = $("#org4SearchDevice").val()
    var mActorId = currentActorId;
    if (orgId != -2)
        mActorId = 3;
    $.ajax({
        url: "../rds_MonitorManage/getStartRoadByRoadName",
        type: "POST",
        data: {
            "roadName": $("#toolBarRoadName").val(),
            "actorIds": mActorId,
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#startRoad4Select").empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#startRoad4Select").append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#startRoad4Select").append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    }
                    else
                        $("#startRoad4Select").append("<option>无</option>");
                } else {
                    $.alert("获取起始道路数据失败", 2);
                }
            }
        }
    })
};

$.getMonitorEndRoad = function (orgId) {
    if (!orgId)
        orgId = $("#org4SearchDevice").val()
    var mActorId = currentActorId;
    if (orgId != -2)
        mActorId = 3;
    $.ajax({
        url: "../rds_MonitorManage/getEndRoadByStartRoad",
        type: "POST",
        data: {
            "city": "",
            "monitorRoadName": $("#toolBarRoadName").val(),
            "startRoad": $("#startRoad4Select").val(),
            "actorIds": mActorId,
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#endRoad4Select").empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#endRoad4Select").append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#endRoad4Select").append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    }
                    else
                        $("#endRoad4Select").append("<option>无</option>");
                } else {
                    $.alert("获取起始道路数据失败", 2);
                }
            }
        }
    })
}

var $getSERoad = _debounce($.getSERoad, 1000);
var $getHighLeverStartRoad = _debounce($.getHighLeverStartRoad, 1000);
var $getMonitorStartRoad = _debounce($.getMonitorStartRoad, 1000);

$.bindDevice = function (deviceId, alarmDeviceId, deviceType) {
    if (gBindDeviceId == null) {
        bootbox.confirm({
            buttons: {
                confirm: {
                    label: '<i class="fa fa-check"></i> 确定',
                    className: 'btn btn-primary btn-flat'
                },
                cancel: {
                    label: '<i class="fa fa-close"></i> 取消',
                    className: 'btn btn-warning btn-flat pull-left'
                }
            },
            message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定要绑定该设备吗？</b>',
            callback: function (result) {
                if (result) {
                    $.ajax({
                        url: "../rds_alarmManage/boundingDevice",
                        type: "POST",
                        data: {
                            deviceId: deviceId,
                            deviceType: deviceType,
                            alarmDeviceId: alarmDeviceId,
                        },
                        success: function (msg) {
                            if (msg) {
                                if (msg.isSuccess && msg.jsonData >= 1) {
                                    $.alert("绑定成功", 1);
                                    deviceListDT.ajax.reload(null, false);
                                    gMainDT.ajax.reload(null, false);
                                    gBindDeviceId = deviceId;
                                    $("#boundingDevice").html(gDeviceType[deviceType] + "." + deviceId)
                                    sendCmdFuc(alarmDeviceId, alarmDeviceId + ",UPDATEALARM")
                                }
                                else
                                    $.alert("绑定失败", 2);
                            } else
                                $.alert("系统错误", 2);
                        }
                    })
                }
            }
        })
    } else $.alert("当前报警器已绑定设备,请先解绑", 2)
}

$.unbindDevice = function (deviceId, alarmDeviceId, deviceType) {
    if (deviceId == gBindDeviceId) {
        bootbox.confirm({
            buttons: {
                confirm: {
                    label: '<i class="fa fa-check"></i> 确定',
                    className: 'btn btn-primary btn-flat'
                },
                cancel: {
                    label: '<i class="fa fa-close"></i> 取消',
                    className: 'btn btn-warning btn-flat pull-left'
                }
            },
            message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定要解除该设备的绑定吗？ 可能会影响其他设备的绑定</b>',
            callback: function (result) {
                if (result) {
                    $.ajax({
                        url: '../rds_alarmManage/unboundingDevice',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            deviceId: deviceId,
                            deviceType: deviceType,
                            alarmDeviceId: alarmDeviceId,
                        },
                        success: function (msg) {
                            if (msg != null && typeof (msg) != "undefined") {
                                if (msg.isSuccess == true) {
                                    $.alert("解绑成功", 1);
                                    deviceListDT.ajax.reload(null, false);
                                    gMainDT.ajax.reload(null, false);
                                    $("#boundingDevice").html("未绑定设备")
                                    gBindDeviceId = null
                                } else {
                                    $.alert("操作失败", 2);
                                }
                            } else {
                                $.alert('系统错误，请联系管理员', 2);
                            }
                        },
                        error: function () {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    });
                }
            }
        });
    } else $.alert("请到绑定设备下解绑该报警器", 2)
}

$.showHighLeverInfo = function (jsonData) {
    console.log(jsonData);
    $("input").attr("readonly", "readonly");
    $("#highLeverLabel").text("信息展示");

    $("#hl_projectNumber").val(jsonData.projectNumber);
    $("#hl_province").val(jsonData.highLeverProvince);
    $("#hl_city").val(jsonData.highLeverCity);
    $("#hl_area").val(jsonData.highLeverArea);

    $("#highLeverBtn").attr("onclick", "$.showMap(" + jsonData.highLeverLongitude + "," + jsonData.highLeverLatitude + ")");
    $("#hl_coordinate").val(jsonData.highLeverLongitude + "," + jsonData.highLeverLatitude);
    $("#highLeverRoadName").val(jsonData.highLeverRoadName);
    $("#highLeverStartRoad").val(jsonData.highLeverStartRoad);
    $("#highLeverEndRoad").val(jsonData.highLeverEndRoad);
    $("#highLeverBrand").val(jsonData.highLeverBrand);
    $("#highLeverInstallOrg").val(jsonData.highLeverInstallOrg);
    $("#highLeverInstallTime").val(jsonData.highLeverInstallTime);
    $("#highLeverRemark").val(jsonData.highLeverRemark);
    $("#highLeverOrgName").val(jsonData.highLeverOrgName);
    $("#highLeverPhotoImg").attr("src", jsonData.highLeverPhoto);
    $("#highLeverPeriod").val(jsonData.highLeverPeriod);
    $("#highLeverServiceLife").val(jsonData.highLeverServiceLife);
    $("#highLeverMainOrgId").val(jsonData.highLeverMainOrgName);
    $("#highLeverSize").val(jsonData.highLeverSize);
    $("#highLeverId").val(jsonData.highLeverId);
    $("#highLeverCreatorName").val(jsonData.highLeverCreatorName);
    $("#highLeverCreatorId").val(jsonData.highLeverCreatorId);
    $("#highLeverModifierId").val(gUserLoginResult.userId);
    $("#highLeverOrgId").val(jsonData.highLeverOrgId);
    $("#highLeverPhoto").val(jsonData.highLeverPhoto);
    $("#highLeverModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });

}

$.showSignalLampInfo = function (jsonData) {
    console.log(jsonData);
    $("input").attr("readonly", "readonly");
    $("#signalLampLabel").text("信息展示");

    $("#sl_projectNumber").val(jsonData.projectNumber);
    $("#sl_province").val(jsonData.signalLampProvince);
    $("#sl_city").val(jsonData.signalLampCity);
    $("#sl_area").val(jsonData.signalLampArea);

    $("#signalLampBtn").attr("onclick", "$.showMap(" + jsonData.signalLampLongitude + "," + jsonData.signalLampLatitude + ")");
    $("#sl_coordinate").val(jsonData.signalLampLongitude + "," + jsonData.signalLampLatitude);
    $("#signalLampStartRoad").val(jsonData.signalLampStartRoad);
    $("#signalLampEndRoad").val(jsonData.signalLampEndRoad);
    $("#signalLampBrand").val(jsonData.signalLampBrand);
    $("#signalLampInstallOrg").val(jsonData.signalLampInstallOrg);
    $("#signalLampInstallTime").val(jsonData.signalLampInstallTime);
    $("#signalLampRemark").val(jsonData.signalLampRemark);
    $("#signalLampOrgName").val(jsonData.signalLampOrgName);
    $("#signalLampPhotoImg").attr("src", jsonData.signalLampPhoto);
    $("#signalLampPeriod").val(jsonData.signalLampPeriod);
    $("#signalLampServiceLife").val(jsonData.signalLampServiceLife);
    $("#signalLampMainOrgId").val(jsonData.signalLampMainOrgName);
    $("#signalLampTypeBtn").val(jsonData.signalLampType);
    $("#signalLampNumber").val(jsonData.signalLampNumber);
    $("#signalLampId").val(jsonData.signalLampId);
    $("#signalLampIsAlarm").val(jsonData.signalLampIsAlarm);
    $("#signalLampCreatorName").val(jsonData.signalLampCreatorName);
    $("#signalLampCreatorId").val(jsonData.signalLampCreatorId);
    $("#signalLampModifierId").val(gUserLoginResult.userId);
    $("#signalLampOrgId").val(jsonData.signalLampOrgId);
    $("#signalLampPhoto").val(jsonData.signalLampPhoto);

    $("#signalLampModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });

}

$.showSolarEnergyInfo = function (jsonData) {
    console.log(jsonData);
    $("input").attr("readonly", "readonly");
    $("#solarEnergyLabel").text("信息展示");

    $("#so_projectNumber").val(jsonData.projectNumber);
    $("#so_province").val(jsonData.solarEnergyProvince);
    $("#so_city").val(jsonData.solarEnergyCity);
    $("#so_area").val(jsonData.solarEnergyArea);

    $("#solarEnergyBtn").attr("onclick", "$.showMap(" + jsonData.solarEnergyLongitude + "," + jsonData.solarEnergyLatitude + ")");
    $("#so_coordinate").val(jsonData.solarEnergyLongitude + "," + jsonData.solarEnergyLatitude);
    $("#solarEnergyRoadName").val(jsonData.solarEnergyRoadName);
    $("#solarEnergyStartRoad").val(jsonData.solarEnergyStartRoad);
    $("#solarEnergyEndRoad").val(jsonData.solarEnergyEndRoad);
    $("#solarEnergyBrand").val(jsonData.solarEnergyBrand);
    $("#solarEnergyInstallOrg").val(jsonData.solarEnergyInstallOrg);
    $("#solarEnergyInstallTime").val(jsonData.solarEnergyInstallTime);
    $("#solarEnergyRemark").val(jsonData.solarEnergyRemark);
    $("#solarEnergyOrgName").val(jsonData.solarEnergyOrgName);
    $("#solarEnergyPhotoImg").attr("src", jsonData.solarEnergyPhoto);
    $("#solarEnergyPeriod").val(jsonData.solarEnergyPeriod);
    $("#solarEnergyServiceLife").val(jsonData.solarEnergyServiceLife);
    $("#solarEnergyMainOrgId").val(jsonData.solarEnergyMainOrgName);
    $("#solarEnergyType").val(jsonData.solarEnergyType);
    $("#solarEnergyMaterial").val(jsonData.solarEnergyMaterial);
    $("#solarEnergyStyle").val(jsonData.solarEnergyStyle);
    $("#solarEnergyId").val(jsonData.solarEnergyId);
    $("#solarEnergyCreatorName").val(jsonData.solarEnergyCreatorName);
    $("#solarEnergyCreatorId").val(jsonData.solarEnergyCreatorId);
    $("#solarEnergyModifierId").val(gUserLoginResult.userId);
    $("#solarEnergyOrgId").val(jsonData.solarEnergyOrgId);
    $("#solarEnergyPhoto").val(jsonData.solarEnergyPhoto);

    $("#solarEnergyModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
}

$.showSignalMachineInfo = function (jsonData) {
    console.log(jsonData);
    $("input").attr("readonly", "readonly");
    $("#signalMachineLabel").text("信息展示");

    $("#sm_projectNumber").val(jsonData.projectNumber);
    $("#sm_province").val(jsonData.signalMachineProvince);
    $("#sm_city").val(jsonData.signalMachineCity);
    $("#sm_area").val(jsonData.signalMachineArea);

    $("#signalMachineBtn").attr("onclick", "$.showMap(" + jsonData.signalMachineLongitude + "," + jsonData.signalMachineLatitude + ")");
    $("#sm_coordinate").val(jsonData.signalMachineLongitude + "," + jsonData.signalMachineLatitude);
    $("#signalMachineStartRoad").val(jsonData.signalMachineStartRoad);
    $("#signalMachineEndRoad").val(jsonData.signalMachineEndRoad);
    $("#signalMachineBrand").val(jsonData.signalMachineBrand);
    $("#signalMachineInstallOrg").val(jsonData.signalMachineInstallOrg);
    $("#signalMachineInstallTime").val(jsonData.signalMachineInstallTime);
    $("#signalMachineRemark").val(jsonData.signalMachineRemark);
    $("#signalMachineOrgName").val(jsonData.signalMachineOrgName);
    $("#signalMachinePhotoImg").attr("src", jsonData.signalMachinePhoto);
    $("#signalMachinePeriod").val(jsonData.signalMachinePeriod);
    $("#signalMachineServiceLife").val(jsonData.signalMachineServiceLife);
    $("#signalMachineMainOrgId").val(jsonData.signalMachineMainOrgName);
    $("#signalMachineType").val(jsonData.signalMachineType);
    $("#signalMachineNumber").val(jsonData.signalMachineNumber);
    $("#signalMachineId").val(jsonData.signalMachineId);
    $("#signalMachineIsAlarm").val(jsonData.signalMachineIsAlarm);
    $("#signalMachineCreatorName").val(jsonData.signalMachineCreatorName);
    $("#signalMachineCreatorId").val(jsonData.signalMachineCreatorId);
    $("#signalMachineModifierId").val(gUserLoginResult.userId);
    $("#signalMachineOrgId").val(jsonData.signalMachineOrgId);
    $("#signalMachinePhoto").val(jsonData.signalMachinePhoto);

    $("#signalMachineModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
}

$.showMonitorInfo = function (jsonData) {
    console.log(jsonData);
    $("input").attr("readonly", "readonly");
    $("#monitorLabel").text("信息展示");

    $("#mo_projectNumber").val(jsonData.projectNumber);
    $("#mo_province").val(jsonData.monitorProvince);
    $("#mo_city").val(jsonData.monitorCity);
    $("#mo_area").val(jsonData.monitorArea);

    $("#monitorBtn").attr("onclick", "$.showMap(" + jsonData.monitorLongitude + "," + jsonData.monitorLatitude + ")");
    $("#mo_coordinate").val(jsonData.monitorLongitude + "," + jsonData.monitorLatitude);
    $("#monitorRoadName").val(jsonData.monitorRoadName);
    $("#monitorStartRoad").val(jsonData.monitorStartRoad);
    $("#monitorEndRoad").val(jsonData.monitorEndRoad);
    $("#monitorBrand").val(jsonData.monitorBrand);
    $("#monitorInstallOrg").val(jsonData.monitorInstallOrg);
    $("#monitorInstallTime").val(jsonData.monitorInstallTime);
    $("#monitorRemark").val(jsonData.monitorRemark);
    $("#monitorOrgName").val(jsonData.monitorOrgName);
    $("#monitorPhotoImg").attr("src", jsonData.monitorPhoto);
    $("#monitorPeriod").val(jsonData.monitorPeriod);
    $("#monitorServiceLife").val(jsonData.monitorServiceLife);
    $("#monitorMainOrgId").val(jsonData.monitorMainOrgName);
    $("#monitorDirection").val(jsonData.monitorDirection);
    $("#monitorPoleShape").val(jsonData.monitorPoleShape);
    $("#monitorPosition").val(jsonData.monitorPosition);
    $("#monitorPoleSize").val(jsonData.monitorPoleSize);
    $("#monitorSize").val(jsonData.monitorSize);
    $("#monitorId").val(jsonData.monitorId);
    $("#monitorCreatorName").val(jsonData.monitorCreatorName);
    $("#monitorCreatorId").val(jsonData.monitorCreatorId);
    $("#monitorModifierId").val(gUserLoginResult.userId);
    $("#monitorOrgId").val(jsonData.monitorOrgId);
    $("#monitorPhoto").val(jsonData.monitorPhoto);

    $("#monitorModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
}

$.showMap = function (x, y) {
    X = x;
    Y = y;
    var url = "management/poleMap.html";
    url += "?x=" + x + "&y=" + y + "&z=1";//通过这种方式传参数
    $("#myMap").attr("src", url);
    $("#modal-map").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

$.beDefault = function () {
    $("input").removeAttr("readonly");
}

$.updateAlarm = function (jsonData) {
    alarmFlag = 1;
    $("#deviceModelDetail").val(jsonData.ruleGroupName)
    $("#deviceOrgId").val(jsonData.deviceOrgId);
    $("#alarmId").val(jsonData.alarmId);
    $("#deviceId").val(jsonData.deviceId);
    $("#deviceState").val(jsonData.deviceState);
    $("#deviceModel").val(jsonData.deviceModel);
    $("#deviceManufacturer").val(jsonData.deviceManufacturer);
    $("#deviceAddress").val(jsonData.deviceAddress);
    $("#createTime").val(jsonData.createTime);
    $("#cycleTime").val(jsonData.cycleTime);
    $("#specialPoint").val(jsonData.specialPoint);
    $("#modal-alarm").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

$.showRecord = function (deviceId) {
    sessionStorage.deviceId = deviceId;
    $.loadURL('报警器管理', '日志信息', 'management/alarmRecord.html', '2', '2', '2', '2', '2')
};

$('#form-alarm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        deviceId: {
            validators: {
                notEmpty: {message: '设备码不能为空'},
                stringLength: {max: 20, message: '设备码长度不超过20'}
            }
        },
        deviceModel: {
            validators: {
                notEmpty: {message: '规则不能为空'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var $form = $(e.target);
    var url;
    var formData = $form.serialize();
    if (alarmFlag == 0)
        url = "../rds_alarmManage/addAlarm";
    else
        url = "../rds_alarmManage/updateAlarm";
    if ($("#deviceOrgId").val() && $("#deviceModelDetail").val()) {
        $.ajax({
            url: url,
            type: 'post',
            data: formData,
            dataType: 'json',
            success: function (msg) {
                if (msg) {
                    if (msg.isSuccess == true) {
                        $.alert("数据操作成功", 1);
                        gMainDT.ajax.reload(null, false);
                        $.clearModal($('#form-alarm'), $('#modal-alarm'));
                    } else {
                        $.alert("数据操作失败", 2);
                    }
                } else {
                    $.alert('系统错误，请联系管理员', 2);
                }
            },
            error: function () {
                $.alert('系统错误，请联系管理员', 2);
            }
        });
    } else {
        var mDetail = 0, mOrgId = 0;
        if ($("#deviceModelDetail").val()) {
            mDetail++;
        }
        if ($("#deviceOrgId").val()) {
            mOrgId++;
        }
        if (mDetail + mOrgId == 0) {
            $.alert("未选择所属公司和规则型号", 2)
        } else if (mOrgId == 0) {
            $.alert("未选择公司类型", 2)
        } else if (mDetail == 0) {
            $.alert("未选择规则型号", 2)
        }
        $(this)
            .bootstrapValidator('disableSubmitButtons', false)
    }

});

$.deleteAlarm = function (alarmId) {
    var count = 1;
    if (alarmId == 0) {
        count = $("input:checkbox[id^='checkbox']:checked").length;
        if (count == 0) {
            $.alert("请选择要删除的数据", 2);
            return;
        } else {
            alarmId = "";
            $("input:checkbox[id^='checkbox']:checked").each(function () {
                alarmId += $(this).val() + ",";
            });
            alarmId = alarmId.substring(0, alarmId.length - 1);
        }
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该' + count + '条数据吗?</b><br><b>该操作会删除报警器对应的所有端口信息！</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: '../rds_alarmManage/deleteAlarmById',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "alarmIds": alarmId
                    },
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                $.alert("数据删除成功", 1);
                                gMainDT.ajax.reload(null, false);
                            } else {
                                $.alert("数据删除失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function () {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
};


$("#inputTypeId").change(function () {
    if ($(this).val() == "2") {
        $(".setpara").hide();
        $(".setkey").show();
    } else {
        $(".setpara").show();
        $(".setkey").hide();
    }

})

$("#sendCmd").click(function () {
    var cmd = $("#cmd").val();
    var deviceId = $("#cmd_deviceId").val();
    var type = $("#cmdSelect").val();
    if (!type || type == 3 && cmd.length <= 0) {
        $.alert("请输入相关指令", 1);
        return;
    }
    switch (type) {
        case "1":
            cmd = deviceId + ",UPDATEALARM";
            break;

        case "2":
            cmd = deviceId + ",UPDATERULE";
            break;

        case "3":
            cmd = deviceId + ",SFS," + cmd;
            break;
        case "4":
            cmd = deviceId + ",SFS,nbsvr getsetting";
            break;
        case "5":
            cmd = deviceId + ",SFS,nbsvr state";
            break;
        case "21":
            cmd = deviceId + ",UPDATEMODEL";
            break;
    }
    sendCmdFuc(deviceId, cmd)
});

function sendCmdFuc(deviceId, cmd) {
    $.ajax({
        url: "../rds_alarmManage/sendIoCmd",
        type: 'post',
        async: false,
        data: {
            deviceId: deviceId,
            cmd: cmd,
            cycleTime: gCycleTime
        },
        dataType: 'json',
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess == true) {
                    $.alert("数据操作成功", 1);
                    $.clearModal($('#form-cmd'), $('#modal-cmd'))
                } else {
                    $.alert("数据操作失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
}

$.showRule = function (modelId) {
    var redCount = 0
    var blueCount = 0
    $("#modal_ruleModel").val(modelId)
    redRuleDt = $("#redRuleDt").DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        ordering: false,
        displayLength: 10,
        // autoWidth: false,
        ajax: {
            url: "../rds_ruleGroup/getRedRuleByModelId",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.modelId = modelId;
            }
        },
        columns: [{
            data: "redRuleFlag",
            render: function (data, type, row) {
                if (data == "100") {
                    return "EC10" + redCount++;
                } else {
                    return "EC20" + blueCount++;
                }
            }
        }, {
            data: "redRuleStatus"
        }, {
            data: "redRuleContent",
            render:function (data) {
                return data.split("").reverse().join("")
            }

        }, {
            data: "redRuleFlag",
            render: function (data) {
                if (data == "100")
                    return "无电";
                else
                    return "冲突";
            }
        }],
        language: {
            url: "zh_cn.json"
        },
        dom: "<'row'<'col-md-6'><'#redTool.col-md-6'>r>t<'row'<'col-md-12'>>",
        initComplete: function () {
            $("#redTool").empty();
        },
    });

    blueRuleDt = $("#blueRuleDt").DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        ordering: false,
        displayLength: 10,
        // autoWidth: false,
        ajax: {
            url: "../rds_ruleGroup/getBlueRuleByModelId",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.modelId = modelId;
            }
        },
        columns: [{
            data: "blueRuleName"
        }, {
            data: "blueRuleContent",
            render:function (data) {
                return data.split("").reverse().join("")
            }

        }, {
            data: "blueRuleFlag",
            render: function (data) {
                if (data == 0)
                    return "常亮";
                else
                    return "无电";
            }
        }],
        language: {
            url: "zh_cn.json"
        },
        dom: "<'row'<'col-md-6'><'#blueTool.col-md-6'>r>t<'row'<'col-md-12'p>>",
        initComplete: function () {
            $("#blueTool").empty();
        }
    });
    $("#show_rule-modal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};
